package online.shenme.day13;

public class EatFood {
    public static void main(String[] args) {

        Desk desk = new Desk();

        new Thread(() -> {
            while (true) {
                synchronized (desk.getOb()) {
                    if (desk.getCount() != 0) {
                        if (!desk.isFlag()) {
                            System.out.println(Thread.currentThread().getName() + "做饭");
                            desk.setFlag(true);
                            desk.getOb().notify();
                        } else {
                            try {
                                desk.getOb().wait();
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                    } else break;
                }
            }
        }, "厨师").start();

        new Thread(() -> {
            while (true) {
                synchronized (desk.getOb()) {
                    if (desk.isFlag()) {
                        System.out.print(Thread.currentThread().getName() + "吃饭\t");
                        desk.setCount(desk.getCount() - 1);
                        System.out.println("还剩："+desk.getCount());
                        desk.setFlag(false);
                        desk.getOb().notify();
                    } else if (desk.getCount() != 0) {
                        try {
                            desk.getOb().wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    } else break;
                }
            }
        }, "食客").start();
    }
}

class Desk {
    private boolean flag;
    private final Object ob = new Object();
    private int count = 10;

    public boolean isFlag() {
        return flag;
    }

    public Object getOb() {
        return ob;
    }

    public int getCount() {
        return count;
    }

    public void setCount(int count) {
        this.count = count;
    }

    public void setFlag(boolean flag) {
        this.flag = flag;
    }
}
